from mitmproxy import ctx
from mitmproxy.websocket import WebSocketMessage
import json

class PacketCapture:
    def request(self, flow):
        # 处理普通 HTTP 请求
        request = flow.request
        print("\n=== 新的请求 ===")
        print(f"URL: {request.pretty_url}")
        print(f"方法: {request.method}")
        
        # 处理请求头
        print("请求头:")
        for key, value in request.headers.items():
            print(f"{key}: {value}")
        
        # 处理请求参数
        if request.method == "GET":
            print("\nGET 参数:")
            print(dict(request.query))
        elif request.method == "POST":
            print("\nPOST 参数:")
            try:
                content_type = request.headers.get("content-type", "")
                if "application/json" in content_type:
                    body = json.loads(request.content.decode('utf-8'))
                    print(json.dumps(body, ensure_ascii=False, indent=2))
                elif "application/x-www-form-urlencoded" in content_type:
                    body = request.urlencoded_form
                    print(dict(body))
                else:
                    print(request.content.decode('utf-8'))
            except Exception as e:
                print(f"解析请求体失败: {e}")

    def websocket_message(self, flow):
        # 处理 WebSocket 消息
        if flow.websocket:
            print("\n=== WebSocket 消息 ===")
            print(f"URL: {flow.request.pretty_url}")
            for message in flow.websocket.messages:
                if isinstance(message, WebSocketMessage):
                    try:
                        content = message.content.decode('utf-8')
                        print(f"{'发送' if message.from_client else '接收'}: {content}")
                    except:
                        print(f"{'发送' if message.from_client else '接收'}: [二进制数据]")

addons = [
    PacketCapture()
]